import heapq
import json

from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils
import math
import operator
import re

MINIMUM_SHOULD_MATCH = '5<85% 10<9'
MAX_BRANDS = 40
MAX_CHARACTER = 50
MAX_KEYWORDS = 10
MAX_CATEGORY = 16
CATEGORY_CUTOFF = 0.7


class WechatKOLMatchMiniQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type, nlp_service=None):
        super(WechatKOLMatchMiniQuerier, self).__init__(es, index, doc_type)
        self.nlp_service = nlp_service

    def _build_query(self, args):
        """
        从args创建查询
        :param args:
        :return:
        """

        term = args.get('term', '')
        term = term if term else ''
        filters = args.get('filters', {})
        filters = filters if filters else {}
        order = args.get('order_by', utils.ORDER_OVERALL)
        order = order if order else utils.ORDER_OVERALL
        from_ = args.get('from', 0)
        from_ = from_ if from_ else 0
        size_ = args.get('size', 10)
        size_ = size_ if size_ else 10
        highlight = args.get('highlight', False)
        highlight = highlight if highlight in (True, False) else False

        query = self._gen_query('', term.strip(), filters, order, from_, size_, highlight)
        return query, {}, {'order': order}

    def _build_result(self, es_result, param):
        # keywords = param['keywords']
        order = param['order']
        total = es_result['hits']['total']
        max_score = es_result['hits']['max_score']
        wechat = []

        for hit in es_result['hits']['hits']:
            wechat.append(self.extract_result(hit, max_score, order))

        return {
            'total': total,
            'wechat': wechat,
        }

    def _gen_query(self, query_keywords, term, filters, order, from_, size_, highlight):
        must_clause = []
        filter_clause = []

        if filters:
            filter_clause = self._add_filter_clause(filter_clause, filters, 'keywords')
            if filters.get('category'):
                filters['category'] = [utils.category_smzdm_2_encode(c) for c in filters['category']]
                filter_clause = self._add_filter_clause(filter_clause, filters, 'category', 'should')

            if filters.get('category_media'):
                filters['category_media'] = [utils.category_media_2_encode(c) for c in filters['category_media']]
                filters['category_media_weight'] = [CATEGORY_CUTOFF]
                filter_clause = self._add_filter_clause(filter_clause, filters, 'category_media', 'should')
                filter_clause = self._add_filter_range_clause(filter_clause, filters, 'category_media_weight')

            filter_clause = self._add_filter_clause(filter_clause, filters, 'customer_type', 'should')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'sum_read_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'avg_read_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'max_read_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'sum_like_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'avg_like_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'max_like_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'like_read_ratio')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'timestamp')

            if filters.get('score'):
                filters['score_cal'] = filters['score']
                filter_clause = self._add_filter_range_clause(filter_clause, filters, 'score_cal')

            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'orig_ratio')
            filter_clause = self._add_filter_match(filter_clause, filters, 'biz_code')
            filter_clause = self._add_filter_match(filter_clause, filters, 'biz_name')
            filter_clause = self._add_filter_match(filter_clause, filters, 'biz_info')

        query = {"query": {"bool": {}}}
        if filter_clause:
            query['query']['bool']['filter'] = filter_clause

        if query_keywords.strip() or term.strip():
            query['query']['bool']['must'] = {
                'bool': {
                    'should': [
                        {
                            'match_phrase': {
                                'biz_code': {
                                    'query': term.strip()[0:MAX_CHARACTER],
                                    'slop': 2,
                                    'boost': 2,
                                }
                            }
                        },
                        {
                            'match_phrase': {
                                'biz_name': {
                                    'query': term.strip()[0:MAX_CHARACTER],
                                    'slop': 2,
                                    'boost': 2,
                                }
                            }
                        },
                        {
                            'match_phrase': {
                                'biz_info': {
                                    'query': term.lower().strip()[0:MAX_CHARACTER],
                                    'slop': 2,
                                    'boost': 2,
                                }
                            }
                        },
                        {
                            'match': {
                                'biz_code': {
                                    'analyzer': 'whitespace',
                                    'query': query_keywords,
                                    'boost': 4,
                                    # 'minimum_should_match': MINIMUM_SHOULD_MATCH
                                }
                            }
                        },
                        {
                            'multi_match': {
                                'analyzer': 'whitespace',
                                'query': query_keywords,
                                'fields': ['biz_name_seg', 'biz_info_seg', 'keywords'],
                                'boost': 1
                                # 'minimum_should_match': MINIMUM_SHOULD_MATCH
                            }
                        }
                    ]
                }
            }

        query['sort'] = []
        if order == utils.ORDER_INFLUENCE:
            query['sort'] = [
                {'score_cal': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == utils.ORDER_RELATIVE:
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.1) * Math.log(doc.score_cal.value + 100)"
                        },
                        "order": "desc"
                    },

                },
                {'score_cal': 'desc'}
            ]
        elif order == utils.ORDER_TIMESTAMP:
            query['sort'] = [
                {'timestamp': 'desc'},
                {'score': 'desc'}
            ]
        elif order == 'like_read_ratio':
            query['sort'] = [
                {'like_read_ratio': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == 'avg_read_num':
            query['sort'] = [
                {'avg_read_num': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == 'avg_like_num':
            query['sort'] = [
                {'avg_like_num': "desc"},
                {'_score': 'desc'}
            ]
        elif order == 'max_read_num':
            query['sort'] = [
                {'max_read_num': 'desc'},
                {'_score': 'desc'}
            ]
        elif order == 'max_like_num':
            query['sort'] = [
                {'max_like_num': 'desc'},
                {'_score': 'desc'}
            ]
        else:
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.0) * Math.log(doc.score.value + 0.001)"
                        },
                        "order": "desc"
                    },

                },
                {'score_cal': 'desc'}
            ]

        if filters.get('category'):
            query['sort'] = [{'category_weight': 'desc'}] + query['sort']

        query['from'] = from_
        query['size'] = size_
        query['track_scores'] = True
        if highlight:
            query['highlight'] = {
                "pre_tags": ["<span class='keyword'>"],
                "post_tags": ["</span>"],
                "fields": {"biz_name": {}, "biz_info": {}}
            }
        else:
            query['highlight'] = {
                "pre_tags": [""],
                "post_tags": [""],
                "fields": {"biz_name": {}, "biz_info": {}}
            }

        return query

    @staticmethod
    def _add_filter_match(must_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                must_clause.append({
                    'bool': {cond: clause}
                })
                values = filters[key]
                if isinstance(values, str):
                    values = values.split(' ')
                for fk in values:
                    clause.append({'match': {key: {'query': fk, 'minimum_should_match': MINIMUM_SHOULD_MATCH}}})
        return must_clause

    @staticmethod
    def _add_filter_clause(filter_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        cond: clause
                    }
                })
                for fk in filters[key]:
                    clause.append({'term': {key: fk}})
        return filter_clause

    @staticmethod
    def _add_filter_range_clause(filter_clause, filters, key):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        'must': clause
                    }
                })
                fk = filters[key]
                if not isinstance(fk, list) or len(fk) < 1:
                    pass
                else:
                    min_fk = fk[0]
                    if len(fk) >= 2:
                        max_fk = fk[1]
                    else:
                        max_fk = None
                    if min_fk is not None and min_fk != 'null':
                        clause.append({'range': {key: {"gte": min_fk}}})
                    if max_fk is not None and max_fk != 'null':
                        clause.append({'range': {key: {"lte": max_fk}}})
        return filter_clause

    @staticmethod
    def extract_result(hit, max_score, order, in_keywords=[]):
        if not hit.get('_source'):
            return {}
        source_ = dict(hit['_source'])
        biz_info = source_['biz_info']

        kol_avatar_url = source_['head_img']
        kol_influence_score = source_['score_cal']
        biz_code = source_['biz_code']
        biz_name = source_['biz_name']

        qr_template = "http://mp.weixin.qq.com/mp/qrcode?scene=10000004&size=102&__biz=%s&mid=%s&idx=%s&sn=%s&send_time="
        bid = source_.get('bid')
        mid = source_.get('mid')
        idx = source_.get('idx')
        sn = source_.get('sn')
        qrcode_url = qr_template % (bid, mid, idx, sn)

        # qrcode_url = "http://mp.weixin.qq.com/mp/qrcode?scene=10000004&size=310&__biz=" + str(source_.get('bid'))
        score_ = hit['_score'] #/ (len(in_keywords) + 1)

        keywords = source_['keywords'][0:10]
        h_keywords = keywords
        highlight = hit.get('highlight')
        if highlight:
            h_kol_name = highlight.get('biz_name')
            biz_name = biz_name if not h_kol_name else h_kol_name[0]
            h_kol_info = highlight.get('biz_info')
            biz_info = biz_info if not h_kol_info else h_kol_info[0]
            h_keywords = highlight.get('keywords')
            if h_keywords:
                hk2 = [s.replace("<span class='keyword'>", '').replace("</span>", '') for s in h_keywords]
                if hk2:
                    h_keywords += [k for k in keywords if k not in hk2][0:10]

        # cat = utils.get_class0(source_['categories'], source_['categories_weight'])

        return {
            'biz_name': biz_name,
            'biz_code': biz_code,
            'biz_info': biz_info,
            'qrcode_url': qrcode_url,
            'keywords': h_keywords if h_keywords else keywords[0:10],
            'head_img': kol_avatar_url,
            'score': kol_influence_score,
            'relative': 1 if max_score <= 0 else score_ / max_score,
            # 'max_score': [ max_score],
            'sum_read_num': source_['sum_read_num'],
            'avg_read_num': source_['avg_read_num'],
            'max_read_num': source_['max_read_num'],
            'sum_like_num': source_.get('sum_like_num'),
            'avg_like_num': source_.get('avg_like_num'),
            'max_like_num': source_.get('max_like_num'),
            'like_read_ratio': source_.get('like_read_ratio'),
            'categories': [utils.category_smzdm_2_decode(int(c)) for c in source_.get('categories', [])],
            'categories_media': [utils.category_media_2_decode(c) for c in source_.get('categories_media', [])],
            'timestamp': source_.get('timestamp'),
            'customer_type': source_.get('customer_type'),
            'orig_ratio': source_.get('orig_ratio'),
            'orig_count': source_.get('orig_count'),
            'media_name': source_.get('media_name'),
            'brands': [],  # self.nlp_service.get_brands(source_.get('keywords', []))
        }




